<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use App\Exception\TestException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class TestExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 非指定异常 直接返回
        if (! $this->isValid($throwable)) {
            return $response;
        }

        // 异常处理逻辑 更具具体的业务异常code，返回指定类型的数据
        $code = $throwable->getCode();
        $data = [
            'data'    => [],
            'code'    => 1,
            'message' => 'this is a TestException error code:' . $code,
        ];

        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        //停止 后续异常不获取捕获
        $this->stopPropagation();

        // 返回数据
        return $response->withStatus(401)->withAddedHeader('Content-Type', 'application/json')->withBody(new SwooleStream($data));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof TestException;
    }
}
